﻿package com.midia.playerVideo.controles {
	import flash.display.MovieClip;	
	
	import flash.geom.Rectangle;
	
	import flash.events.Event;
	import flash.events.MouseEvent;	
	import flash.events.EventDispatcher;
	
	import com.midia.playerVideo.events.BarraEvent;
		
	public class BarraProgresso extends MovieClip {
		
		private var _perc:int;
		
		public function BarraProgresso ():void {
			this.drag.buttonMode = true;
			
			this.drag.addEventListener (MouseEvent.MOUSE_DOWN, this.onStartDrag);	
			this.areaSeek.addEventListener (MouseEvent.MOUSE_DOWN, this.onDownArea);			
		}
		
		public function get perc ():int {
			return this._perc;
		}
		
		public function set perc (valor:int):void {
			this._perc = valor;
			this.drag.x = Math.ceil( this._perc * this.area.width / 100);
		}
		
		private function onDownArea (evento:MouseEvent):void {
			var objeto:MovieClip = MovieClip (evento.target);
			var perc:Number = Math.round (objeto.mouseX / objeto.width * 100);	
			
			var evt:BarraEvent = new BarraEvent(BarraEvent.CLICK_AREA);
			evt.perc = perc;
			this.dispatchEvent(evt);
		}
		
		private function onStartDrag (evento:MouseEvent):void {
			var rect:Rectangle = new Rectangle (0, this.drag.y, this.area.width - this.drag.width, 0);
			this.drag.startDrag (false, rect);
			this.drag.addEventListener (MouseEvent.MOUSE_MOVE, this.onMoveDrag);
			
			var evt:BarraEvent = new BarraEvent(BarraEvent.DRAG_START);
			this.dispatchEvent(evt);
			
			this.stage.addEventListener (MouseEvent.MOUSE_MOVE, this.onMoveDrag);
			this.stage.addEventListener (MouseEvent.MOUSE_UP, this.onStopDrag);
			this.drag.addEventListener (MouseEvent.MOUSE_UP, this.onStopDrag);
		}
		
		private function onStopDrag (evento:MouseEvent):void {
			this.drag.stopDrag ();
			this.drag.removeEventListener (MouseEvent.MOUSE_MOVE, this.onMoveDrag);
						
			var evt:BarraEvent = new BarraEvent(BarraEvent.DRAG_STOP);
			evt.perc = this._perc;
			this.dispatchEvent(evt);
			
			/*if (evento.target == circle || this.drag.contains(evento.target as DisplayObject)){
				// onRelease
			}else{
				// onReleaseOutside				
			}*/
			
			this.stage.removeEventListener (MouseEvent.MOUSE_MOVE, this.onMoveDrag);
			this.stage.removeEventListener (MouseEvent.MOUSE_UP, this.onStopDrag);
			this.drag.removeEventListener (MouseEvent.MOUSE_UP, this.onStopDrag);
		}
		
		private function onMoveDrag (evento:Event):void {
			this._perc = Math.ceil(this.drag.x / this.area.width * 100); 	
			this.prog.width = this.drag.x;
			
			var evt:BarraEvent = new BarraEvent(BarraEvent.DRAG_MOVE);
			evt.perc = this._perc;
			this.dispatchEvent(evt);
		}
	}	
}